package com.example.moonshine.redchange.Activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.moonshine.redchange.Data.ChangeDate;
import com.example.moonshine.redchange.Data.LoginData;
import com.example.moonshine.redchange.Data.RSpostData;
import com.example.moonshine.redchange.Data.ResultData;
import com.example.moonshine.redchange.Data.ReturnPostData;
import com.example.moonshine.redchange.Data.ReturnStatusData;
import com.example.moonshine.redchange.Data.SysInfoData;
import com.example.moonshine.redchange.Helper.DataDBHepler;
import com.example.moonshine.redchange.R;
import com.example.moonshine.redchange.Util.DataUrl;
import com.example.moonshine.redchange.Util.DownloadUtil;
import com.example.moonshine.redchange.Util.HttpUtil;
import com.example.moonshine.redchange.Util.SavePamasInfo;
import com.example.moonshine.redchange.Util.SaveParmasUtrl;
import com.example.moonshine.redchange.Util.UpdateDialog;
import com.github.zackratos.ultimatebar.UltimateBar;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static android.content.ContentValues.TAG;

/**
 * Created by moonshine on 2018/1/26.
 */


public class LoginActivity extends Activity {

    private DownloadUtil downloadUtils;
    String updateApkUrl;
    EditText usernameEt;
    EditText passwordEt;
    Button loginBtn;

    DataDBHepler dbHepler=null;
    String  loginStatusCode=null;
    String  userName=null;
    String passWord=null;
    String userCode = null;
    LinearLayout linearLayout;
    SaveParmasUtrl saveParmasUtrl = new SaveParmasUtrl();
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        UltimateBar.newColorBuilder()
                .statusColor(Color.parseColor("#0a3640"))       // 状态栏颜色
                .statusDepth(50)                // 状态栏颜色深度
                .build(this)
                .apply();
        ViewLayout();
        init();
        dbHepler = new DataDBHepler(getBaseContext());
        try {
            userName =saveParmasUtrl.getInfo(LoginActivity.this,"username","login");
            passWord =saveParmasUtrl.getInfo(LoginActivity.this,"password","login");
            usernameEt.setText(userName);
            passwordEt.setText(passWord);
        }catch (Exception e)
        {
            e.printStackTrace();
        }
        usernameEt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                usernameEt.setCursorVisible(true);
                Log.i("tag","消息：点击");
            }
        });
        passwordEt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                passwordEt.setCursorVisible(true);
                Log.i("tag","消息：点击");
            }
        });


    }
        //控件初始化
    @SuppressLint("NewApi")
    public void ViewLayout() {
        loginBtn = findViewById(R.id.login_btn);
        usernameEt = findViewById(R.id.login_user);
        passwordEt = findViewById(R.id.login_psw);
        linearLayout = findViewById(R.id.lineSetCode);

    }


    public void init() {
        Intent intent = getIntent();
        updateApkUrl = intent.getStringExtra("url");
        if (updateApkUrl.equals("null")) {
            Log.i(TAG, "已经为最新版本");
        } else {
            Log.i(TAG, "该下载链接为:" + updateApkUrl);
            showDialog();
        }
    }
        public void showDialog() {
            downloadUtils =   new DownloadUtil(LoginActivity.this);
            final UpdateDialog Dialog = new UpdateDialog(LoginActivity.this);
            Dialog.setTitle("消息提示");
            Dialog.setMessage("发现新版本，是否更新?");
            Dialog.setYesOnclickListener("确定", new UpdateDialog.onYesOnclickListener() {
                @Override
                public void onYesClick() {
                    downloadUtils.downloadAPK(updateApkUrl, "apk");
                    Dialog.dismiss();
                }
            });
            Dialog.setNoOnclickListener("取消", new UpdateDialog.onNoOnclickListener() {
                @Override
                public void onNoClick() {
                    Dialog.dismiss();
                }
            });
            Dialog.show();
        }
//    /**
//     * 获取mac地址
//     * @return  返回mac地址
//     * @throws SocketException
//     */
//    // 有兴趣的朋友可以看下NetworkInterface在Android FrameWork中怎么实现的
//    public static String macAddress() throws SocketException {
//        String address = null;
//        // 把当前机器上的访问网络接口的存入 Enumeration集合中
//        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
//        while (interfaces.hasMoreElements()) {
//            NetworkInterface netWork = interfaces.nextElement();
//            // 如果存在硬件地址并可以使用给定的当前权限访问，则返回该硬件地址（通常是 MAC）。
//            byte[] by = netWork.getHardwareAddress();
//            if (by == null || by.length == 0) {
//                continue;
//            }
//            StringBuilder builder = new StringBuilder();
//            for (byte b : by) {
//                builder.append(String.format("%02X:", b));
//            }
//            if (builder.length() > 0) {
//                builder.deleteCharAt(builder.length() - 1);
//            }
//            String mac = builder.toString();
//            Log.d("mac", "interfaceName="+netWork.getName()+", mac="+mac);
//            // 从路由器上在线设备的MAC地址列表，可以印证设备Wifi的 name 是 wlan0
//            if (netWork.getName().equals("wlan0")) {
//                Log.d("mac", " interfaceName ="+netWork.getName()+", mac="+mac);
//                address = mac;
//            }
//        }
//        return address;
//    }


    //当用户获取焦点 界面显示时
    @Override
    protected void onResume() {
        super.onResume();

        /**
         *
         * 点击事件  获取验证码
         */

        loginBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(final View view) {
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                if (networkInfo == null || !networkInfo.isAvailable()) {
                    Toast.makeText(getApplicationContext(), "网络未连接", Toast.LENGTH_SHORT).show();
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Looper.prepare();
                            try {
                                if(usernameEt.getText().toString().equals("")||passwordEt.getText().toString().equals(""))
                                {
                                    Toast.makeText(LoginActivity.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
                                }
                                loginStatusCode = GetPostLogin(usernameEt.getText().toString(), passwordEt.getText().toString(), new DataUrl().loginUrl);
                            }catch (Exception e)
                            {
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext(),"网络无连接",Toast.LENGTH_SHORT).show();
                            }
                            try {
                                if (loginStatusCode.equals("10")) {
                                    new Thread(){
                                        @Override
                                        public void run() {
                                            SavePamasInfo savePamasInfo = new SavePamasInfo();
                                            savePamasInfo.saveInfo(LoginActivity.this,"userCode",userCode,"login");
                                            saveParmasUtrl.saveInfo(LoginActivity.this,"username",usernameEt.getText().toString().trim(),"login");
                                            saveParmasUtrl.saveInfo(LoginActivity.this,"password",passwordEt.getText().toString().trim(),"login");
//                                            try {
////                                                saveParmasUtrl.saveInfo(LoginActivity.this,"macAddress",macAddress(),"login");
//                                            } catch (SocketException e) {
//                                                e.printStackTrace();
//                                            }
                                        }
                                    }.start();
                                    Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();//提示用户登录成功
                                    Intent intent = new Intent();
                                    intent.setClass(LoginActivity.this, MainActivity.class);
                                    startActivity(intent);
                                    finish();
                                } else if (loginStatusCode.equals("12")) {
                                    Toast.makeText(getApplicationContext(), "登录失败，服务器故障", Toast.LENGTH_SHORT).show();//提示用户登录失败
                                } else if (loginStatusCode.equals("14")) {
                                    new Thread(){
                                        @Override
                                        public void run() {
                                            saveParmasUtrl.saveInfo(LoginActivity.this,"username",usernameEt.getText().toString().trim(),"login");
                                            saveParmasUtrl.saveInfo(LoginActivity.this,"password",passwordEt.getText().toString().trim(),"login");
                                        }
                                    }.start();
                                    Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();//提示用户登录成功

                                    Intent intent = new Intent();
                                    intent.setClass(LoginActivity.this, MainActivity.class);
                                    startActivity(intent);
                                    finish();
                                }else if (loginStatusCode.equals("16")) {

                                    Toast.makeText(getApplicationContext(), "验证码已过期,请重新获取", Toast.LENGTH_SHORT).show();//提示用户登录失败

                                } else if (loginStatusCode.equals("17")) {
                                    Toast.makeText(getApplicationContext(), "验证码错误", Toast.LENGTH_SHORT).show();//提示用户登录失败
                                }else {
                                    Toast.makeText(getApplicationContext(), "登录失败，用户名或密码错误", Toast.LENGTH_SHORT).show();//提示用户登录失败
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext(), "服务器故障", Toast.LENGTH_SHORT).show();//提示用户登录失败
                            }
                            Looper.loop();
                        }
                    }).start();
                }
            }
        });

    }

    /**
     *  用户登录验证
     * @param uname  y用户名
     * @param upsd    密码
     * @param path     请求链接
     * @return    后台返回响应码
     */
    public String GetPostLogin(String uname,String upsd,String path) {
        //okhttp Post请求传输Json数据
        OkHttpClient client = new OkHttpClient();
        LoginData Ldata = new LoginData();
        String postStatus = null;

        //将扫描的结果传输到实体
        Ldata.setUname(uname);
        Ldata.setUpwd(upsd);
        Ldata.setModule("AN4");
        Gson gson = new Gson();
        String json = gson.toJson(Ldata);//将其转换为JSON数据格式

        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");

        RequestBody requestBody = RequestBody.create(mediaType, json);//放进requestBoday中
        Request request = new Request.Builder()
                .url(path)
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String result = response.body().string();
            ReturnStatusData resultStatusData= gson.fromJson(result,ReturnStatusData.class);
            String resultSid = resultStatusData.getSid();
            String resultSysInfo = resultStatusData.getSystemInfo();
            List<SysInfoData> sysInfoData =gson.fromJson(resultSysInfo,new TypeToken<List<SysInfoData>>(){}.getType());
            List sysId =new ArrayList<>();
            List sysname =new ArrayList<>();
            try {
                for (int i=0;i<sysInfoData.size();i++)
                {
                    sysId.add(sysInfoData.get(i).getSysId());
                    sysname.add(sysInfoData.get(i).getSysName());
                    Log.i("tag","sysid："+sysInfoData.get(i).getSysId());
                }
                saveParmasUtrl.saveInfo(this,"sysids",String.valueOf(sysId).replace("[","").replace("]",""),"login");
                saveParmasUtrl.saveInfo(this,"sysname",String.valueOf(sysname).replace("[","").replace("]",""),"login");
                saveParmasUtrl.saveInfo(this,"sid",resultSid,"login");
            } catch (Exception e) {
                e.printStackTrace();
            }

            Log.i(TAG,"SID为"+resultSid);
            Log.i(TAG,"SysId为"+resultSysInfo);
            postStatus= resultStatusData.getStatus();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(LoginActivity.this,"请求超时",Toast.LENGTH_SHORT).show();
        }
        return postStatus;
    }

}
